package com.huaju.enity;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import static org.hibernate.criterion.Example.create;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;




/**
 * A data access object (DAO) providing persistence and search support for
 * Profit entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.huaju.enity.Profit
 * @author MyEclipse Persistence Tools
 */
@Transactional
public class ProfitDAO {
	private static final Logger log = LoggerFactory.getLogger(ProfitDAO.class);
	// property constants
	public static final String IDESC = "idesc";
	public static final String IMONEY = "imoney";
	public static final String SUCCESS = "success";

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	protected void initDao() {
		// do nothing
	}

	public boolean save(Profit transientInstance) {
		log.debug("saving Profit instance");
		try {
			getCurrentSession().save(transientInstance);
			log.debug("save successful");
			return true;
		} catch (RuntimeException re) {
			log.error("save failed", re);
			return false;
		}
	}
	public void saveOrUpdate(Profit transientInstance) {
		log.debug("saving Profit instance");
		try {
			getCurrentSession().saveOrUpdate(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Profit persistentInstance) {
		log.debug("deleting Profit instance");
		try {
			getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Profit findById(java.lang.Integer id) {
		log.debug("getting Profit instance with id: " + id);
		try {
			Profit instance = (Profit) getCurrentSession().get(
					"com.huaju.enity.Profit", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<Profit> findByExample(Profit instance) {
		log.debug("finding Profit instance by example");
		try {
			List<Profit> results = (List<Profit>) getCurrentSession()
					.createCriteria("com.huaju.enity.Profit")
					.add(create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Profit instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Profit as model where model."
					+ propertyName + "= ?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	public Double getIncomeProfitByUser(Integer aid) {
		log.debug("finding all Profit instances");
		try {
			String queryString = " SELECT Sum(imoney) FROM profit where aid ="+aid+" and ptype=5";
			SQLQuery queryObject = getCurrentSession().createSQLQuery(queryString);
			if(queryObject.list()!=null)
			{
				try {
					System.out.println("profit:"+queryObject.list().get(0).toString());
					return Double.parseDouble(queryObject.list().get(0).toString());
				} catch (Exception e) {
					// TODO: handle exception
					return 0.00;
				}
				
			}
			return 0.00;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	
	public Double getPayProfitByUser(Integer aid) {
		log.debug("finding all Profit instances");
		try {
			String queryString = " SELECT Sum(imoney) FROM profit where aid="+aid+" and ptype in (3,4) ";
			SQLQuery queryObject = getCurrentSession().createSQLQuery(queryString);
			if(queryObject.list()!=null)
			{
				try {
					System.out.println("profit2:"+queryObject.list().get(0).toString());
					return Double.parseDouble(queryObject.list().get(0).toString());
				} catch (Exception e) {
					// TODO: handle exception
					return 0.00;
				}
				
			}
			return 0.00;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	public Integer countAll(String pro,Object value,short type) {
		log.debug("finding all Profit instances");
		try {
			String queryString = "from Profit model where model."+pro+"=? and success=? ";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			queryObject.setParameter(1, type);
			return queryObject.list().size();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	
	public List findByPage(Integer start,Integer size,String pro,Object value,short type) {
		log.debug("finding all Profit instances");
		try {
			String queryString = "from Profit model where model."+pro+"=? and success=? order by pid desc";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			queryObject.setParameter(1, type);
			queryObject.setMaxResults(size);
			queryObject.setFirstResult(start);
			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List<Profit> findByIdesc(Object idesc) {
		return findByProperty(IDESC, idesc);
	}

	public List<Profit> findByImoney(Object imoney) {
		return findByProperty(IMONEY, imoney);
	}

	public List<Profit> findBySuccess(Object success) {
		return findByProperty(SUCCESS, success);
	}

	public List findAll() {
		log.debug("finding all Profit instances");
		try {
			String queryString = "from Profit";
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List findTotalAnalysis(Integer comId ,String month,Integer ptype) {
		try {
			String queryString = "select count(*),sum(imoney) from profit where ptype=? and  successTime > ?";
			if (comId != null) {
				queryString += " and comId="+ comId;
			}
			SQLQuery queryObject = getCurrentSession().createSQLQuery(
					queryString);
			queryObject.setParameter(0, ptype);
			queryObject.setParameter(1, month);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	public Integer countAll(short type) {
		log.debug("finding all Profit instances");
		try {
			String queryString = "from Profit where success=?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, type);
			return queryObject.list().size();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	public List findByPage(Integer start,Integer size,short type) {
		log.debug("finding all Profit instances");
		try {
			String queryString = "from Profit where success=? order by pid desc";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, type);
			queryObject.setMaxResults(size);
			queryObject.setFirstResult(start);
			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Profit merge(Profit detachedInstance) {
		log.debug("merging Profit instance");
		try {
			Profit result = (Profit) getCurrentSession()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Profit instance) {
		log.debug("attaching dirty Profit instance");
		try {
			getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Profit instance) {
		log.debug("attaching clean Profit instance");
		try {
			getCurrentSession().buildLockRequest(LockOptions.NONE).lock(
					instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static ProfitDAO getFromApplicationContext(ApplicationContext ctx) {
		return (ProfitDAO) ctx.getBean("ProfitDAO");
	}
	
	public Double getIncomeProfitByUser(Integer aid,Integer type) {
		log.debug("finding all Profit instances");
		try {
			String queryString = " SELECT Sum(imoney) FROM profit where aid ="+aid+" and ptype=5  and success=?";
			SQLQuery queryObject = getCurrentSession().createSQLQuery(queryString);
			queryObject.setParameter(0, type);
			if(queryObject.list()!=null)
			{
				try {
					System.out.println("profit:"+queryObject.list().get(0).toString());
					return Double.parseDouble(queryObject.list().get(0).toString());
				} catch (Exception e) {
					// TODO: handle exception
					return 0.00;
				}
				
			}
			return 0.00;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public Double getPayProfitByUser(Integer aid,Integer type) {
		log.debug("finding all Profit instances");
		try {
			String queryString = " SELECT Sum(imoney) FROM profit where aid="+aid+" and ptype in (3,4)  and success=?";
			SQLQuery queryObject = getCurrentSession().createSQLQuery(queryString);
			queryObject.setParameter(0, type);
			if(queryObject.list()!=null)
			{
				try {
					System.out.println("profit2:"+queryObject.list().get(0).toString());
					return Double.parseDouble(queryObject.list().get(0).toString());
				} catch (Exception e) {
					// TODO: handle exception
					return 0.00;
				}
				
			}
			return 0.00;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List findApplyItems(String propertyName, Object value) {
		log.debug("finding Profit instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Profit as model where model."
					+ propertyName + "= ? and model.success=0";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	/**
	 * 
	 * @param day  0:当天
	 * @return
	 */
	public List findLastDayList(Integer day,Integer uid) {
		log.debug("finding all Payoutlist instances");
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 Calendar todayStart = Calendar.getInstance(); 
			 todayStart.add(Calendar.DAY_OF_MONTH,-day);  
			 todayStart.set(Calendar.AM_PM,0);
		        todayStart.set(Calendar.HOUR, 0);  
		        todayStart.set(Calendar.MINUTE, 0);  
		        todayStart.set(Calendar.SECOND, 0);  
			Date todayTime = todayStart.getTime();  
			String queryString = "from Profit u where u.itime >=:date  and u.account.aid= "+uid+" order by u.itime desc";
//			String queryString = "from User";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setTimestamp("date", todayTime);
//			queryObject.setTimestamp("beginDate", todayTime);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List<Profit> findListByType(Integer page, Integer size, Integer type,Integer uid) {
		String queryString;
		Query q ;
		try {
			if(type==-1){
				queryString = "from Profit msg where msg.account.aid= "+uid+" and success!=3 and success!=4 order by msg.itime desc";
			}else{
				queryString = "from Profit msg where msg.ptype="+type+" and msg.account.aid= "+uid+"  and success!=3 and success!=4 order by msg.itime desc";
			}
			q = getCurrentSession().createQuery(queryString);
			q.setFirstResult(page*size);
			q.setMaxResults(size);
			return q.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public Double findLastDayIncome(Integer uid) {
		log.debug("finding all Payoutlist instances");
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 Calendar todayStart = Calendar.getInstance(); 
			 todayStart.add(Calendar.DAY_OF_MONTH,-1);  
			 todayStart.set(Calendar.AM_PM,0);
		        todayStart.set(Calendar.HOUR, 0);  
		        todayStart.set(Calendar.MINUTE, 0);  
		        todayStart.set(Calendar.SECOND, 0);  
			Date todayTime = todayStart.getTime();  
			String queryString = "select * from profit u where u.itime >=:date and u.ptype=5 and u.aid= "+uid+" order by u.itime desc";
//			String queryString = "from User";
			SQLQuery queryObject = getCurrentSession().createSQLQuery(queryString).addEntity(Profit.class);
			queryObject.setTimestamp("date", todayTime);
//			queryObject.setTimestamp("beginDate", todayTime);
			List<Profit> list = queryObject.list();
			if(list!=null&&list.size()>0){
				return list.get(0).getImoney();
			}else{
				return null;
			}
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	
	public List<Profit> findUserIncomeByPage(int page, int size, Integer aid) {
		String queryString;
		Query q ;
		try {
			 queryString = "from Profit msg where msg.account.aid = "+aid+" and  success !=3 and success !=4 order by msg.itime desc";
			 q = getCurrentSession().createQuery(queryString);
			q.setFirstResult(page*size);
			q.setMaxResults(size);
			return q.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
}